qui(function (require, exports, module) {
    Zhibo.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            channel_status: function (cellvalue, options, rowObject) {
                if (cellvalue == 1) {
                    return "收录中"
                } else if (cellvalue == null) {
                    return "错误";
                }
                return "未收录";
            },
            freeType: function (cellvalue, options, rowObject) {
                if (cellvalue == 1) {
                    return "是"
                }
                return "否"
            },
            channel_ip: function (cellvalue, options, rowObject) {
                if (cellvalue == null || Zhibo.Config.IP_LINK_AREA[cellvalue] == null) {
                    return "未知"
                }
                return Zhibo.Config.IP_LINK_AREA[cellvalue]
            },
            operate2: function (cellvalue, options, rowObject) {
                //收录/停止收录,打点,新打点,修改,加入预览,编码参数，编码详情,预置收录，定时开启,删除,日志
                var htmlArr = ["", "", "", "", "", "", "", "", "", "", "",""];
                var disabledValue = rowObject.channel_status === 0 ? 'disabled="disabled"' : ""
                var emptyValue = rowObject.channel_status === 0 ? "" : 'disabled="disabled"'
                if (Zhibo.Config.AUTH_BASE) {
                    htmlArr[4] = '<button onclick="Zhibo.Util.addMonitor(' + rowObject.channel_id + ')" type="button" rtmp="' + rowObject.rtmp + '" channel-id="' + rowObject.channel_id + '" class="btn btn-default addMonitor" ' + disabledValue + ' >加入预览</button>';
                    htmlArr[2] = '<button onclick="Zhibo.Util.addPointEPG2(' + rowObject.channel_id + ')" type="button" channel-id="' + rowObject.channel_id + '" class="btn btn-default pointer" ' + disabledValue + ' >新打点</button>';
                    if (Zhibo.Config.GREY_MODE.containsObj({ ip:rowObject.channel_ip })) {
                        htmlArr[11] = '<button onclick="Zhibo.Util.openWrapSys(' + rowObject.channel_id + ')" type="button" channel-id="' + rowObject.channel_id + '" class="btn btn-default pointer" ' + disabledValue + ' >包装系统</button>';
                    }
                }
                if (Zhibo.Config.AUTH_SENIOR) {
                    if (rowObject.hasOwnProperty('channel_status')) {
                        if (rowObject.channel_status === 0) {
                            htmlArr[0] = '<button type="button" onclick="Zhibo.Util.startRecord(' + rowObject.channel_id + ')" class="btn btn-default start_record" style="margin-left: 24px">收录</button>';
                        } else if (rowObject.channel_status === 1) {
                            htmlArr[0] = '<button type="button" onclick="Zhibo.Util.stopRecord(' + rowObject.channel_id + ')" class="btn btn-default stop_record">停止收录</button>';
                        }
                    }
                    htmlArr[3] = '<button onclick="Zhibo.Util.changeElement(' + rowObject.channel_id + ')" type="button" rtmp="' + rowObject.rtmp + '" class="btn btn-default change" ' + emptyValue + ' >修改</button>';
                    htmlArr[5] = '<button onclick="Zhibo.Util.jumpToCodeEdit(' + rowObject.channel_id + ')" type="button" class="btn btn-default modify-code-pram" ' + emptyValue + ' >编码参数</button>';
                    htmlArr[6] = '<button onclick="Zhibo.Util.showCodeDetail(\'' + rowObject.channel_ip + '\', \'' + rowObject.channel_code + '\')" type="button" class="btn btn-default modify-code-pram" >编码详情</button>';
                    //htmlArr[5] = '<a href="http://lego.iqiyi.com/live2VOD/preSet/home?channel_name=' + rowObject.channel_name + '&channel_id=' + rowObject.channel_id + '" target="_blank" style="margin-right:15px;" class="btn btn-default">预置收录</a>';
                    htmlArr[7] = '<a href="./live2VOD_preset_home.html?channel_name=' + rowObject.channel_name + '&channel_id=' + rowObject.channel_id + '" target="_blank" style="margin-right:15px;" class="btn btn-default">预置收录</a>';
                    htmlArr[9] = '<button onclick="Zhibo.Util.delElement(' + rowObject.channel_id + ')" type="button" class="btn btn-default del" ' + emptyValue + ' >删除</button>'
                    htmlArr[10] = '<button onclick="Zhibo.Util.openHistory(' + rowObject.channel_id + ')" type="button" class="btn btn-default history" >日志</button>'
                    htmlArr[8] = '<button onclick="Zhibo.Util.openRecord(' + rowObject.channel_id + ')" type="button" class="btn btn-default history" >定时收录</button>'
                }
                return htmlArr.join("");
            },
            region: function (cellvalue, options, rowObject) {
                var htmlArr = [];
                $.each(Zhibo.Config.REGION_CH_LIST, function (i, element) {
                    htmlArr.push("<option value='" + i + "' " + (i == cellvalue ? "selected='selected'" : "") + ">" + element + "</option>")
                })
                return '<select class="input-medium"><option value="">请选择</option>' + htmlArr.join("") + '</select>';
            },
            operate3: function (cellvalue, options, rowObject) {
                return '<button type="button" onclick="Zhibo.Util.IpModify(' + rowObject.id + ')">修改</button>|<button type="button" onclick="Zhibo.Util.IpDel(' + rowObject.id + ')">删除</button>';
            },
            log_type: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Zhibo.Dao.logType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.descr;
                        return true;
                    }
                })
                return ret;
            },
            record_operate: function (cellvalue, options, rowObject) {
                return '<button type="button" onclick="Zhibo.Util.modifyRecord(' + rowObject.id + ')">编辑</button>|<button type="button" onclick="Zhibo.Util.delRecord(' + rowObject.id + ')">删除</button>';
            },
            log_descr: function (cellvalue, options, rowObject) {
                var ret = cellvalue;
                if (rowObject.type == 107 || rowObject.type == 108) {
                    try {
                        ret = Zhibo.Util.decodeDescription(cellvalue)
                    } catch (exception) {
                        console.log("has error ; rowObject.id  " + rowObject.id);
                        ret = cellvalue;
                    }
                }
                return  ret;
            }
        },
        setContainer: function ($container) {
            this.$container = $container;
        },
        startRecord: function (elementId) {
            SystemDialog.queryConfirm("是否确定要收录操作？", function (flag) {
                if (flag) {
                    var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
                    req_publicparams["func"] = "enable";
                    Zhibo.Util.modifyChannel(req_publicparams, elementId);
                }
            });
        },

        stopRecord: function (elementId) {
            SystemDialog.queryConfirm("是否确定要停止收录操作？", function (flag) {
                if (flag) {
                    var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
                    req_publicparams["func"] = "disable";
                    Zhibo.Util.modifyChannel(req_publicparams, elementId);
                }
            });
        },
        delElement: function (elementId) {
            SystemDialog.queryConfirm("是否确定要删除操作？", function (flag) {
                if (flag) {
                    var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
                    req_publicparams["func"] = "delete_channel";
                    Zhibo.Util.modifyChannel(req_publicparams, elementId);
                }
            });
        },
        addPointEPG: function (elementId) {
            var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
            window.open('/epg/dadian.html?' + req_publicparams['channel_code'] + '=' + req_publicparams['channel_ip'] + '&free_type=' + req_publicparams["freeType"] + '&channel_id=' + elementId + '&cn=' + req_publicparams['channel_name'] + '&location=' + req_publicparams['location'] + '&locationCategory=' + req_publicparams['locationCategory'], "epg" + req_publicparams['channel_code']);
        },
        addPointEPG2: function (elementId) {
            var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
            window.open('/epg/dadian_news_merge.html?' + req_publicparams['channel_code'] + '=' + req_publicparams['channel_ip'] + '&free_type=' + req_publicparams["freeType"] + '&channel_id=' + elementId + '&cn=' + req_publicparams['channel_name'] + '&location=' + req_publicparams['location'] + '&locationCategory=' + req_publicparams['locationCategory'], "epg" + req_publicparams['channel_code']);
        },

        addPoint: function (elementId) {
            var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
            window.open('/peditor/home_epg?' + req_publicparams['channel_code'] + '=' + req_publicparams['channel_ip'] + '&free_type=' + req_publicparams["freeType"] + '&channel_id=' + elementId + '&cn=' + req_publicparams['channel_name'] + '&location=' + req_publicparams['location'] + '&locationCategory=' + req_publicparams['locationCategory'], req_publicparams['channel_code']);
        },
        buildPublicParams: function (elementId) {
            var selectElement = Zhibo.Util.getSelectElement(elementId);
            var publicParams = {
                "src_channel_ip": selectElement.channel_ip,
                "channel_ip": selectElement.channel_ip,
                "src_channel_addr": selectElement.channel_addr,
                "channel_addr": selectElement.channel_addr,
                "channel_name": selectElement.channel_name,
                "channel_code": selectElement.channel_code,
                "location": selectElement.location,
                "locationCategory": selectElement.loc_id,
                "freeType": selectElement.freeType,
                //   "index"				:	$.trim($("table#channel_list tr").index($(this).parents("tr"))),
                "type": $("#myTab li.active").attr("value"),
                "src_channel_code": selectElement.channel_code
            };

            return publicParams;
        },
        addChannel: function ($data) {
            if ($.isEmptyObject($data)) {
                EpgWeb.Plugin.showTips({"type": "error", "content": "接口ADD_CHANNEL参数不能为空"})
                return;
            }
            $data['username'] = $("div.user a.name").html();
            $data['from_client'] = true;
            Zhibo.Dao.addChannel($data, function (data) {
                if (data == null) {
                    EpgWeb.Plugin.showTips({"type": "error", "content": "/channel/modify 接口异常"})
                    return;
                }
                if (data.code != null && data.code == 200) {
                    if (parseInt(data['response']['status']) == 0) {
                        Zhibo.Config.WAIT_ADD_DATA = $data;
                        EpgWeb.Plugin.showTips({ "content": "success"});
                        $("button[name=channelQuery]").click();
                    } else {
                        EpgWeb.Plugin.showTips({"type": "error", "content": data['response']['error']})
                    }
                }
            });
        },
        modifyChannel: function ($data, elementId) {
            if ($data === undefined || $data == null || !$data.hasOwnProperty('func')) {
                EpgWeb.Plugin.showTips({"type": "error", "content": "操作频道失败:参数不完整"})
                return;
            }
            if (-1 == $.inArray($data['func'], Zhibo.Config.FUNC_EXTENT)) {
                EpgWeb.Plugin.showTips({"type": "error", "content": "操作频道失败:" + $data['func'] + "方法不支持"});
                return;
            }
            $data['username'] = $("div.user a.name").html();
            $data['from_client'] = true;
            Zhibo.Dao.modifyChannel($data, function (data) {
                var modifyResult = {result: "log error"}
                if (data == null) {
                    EpgWeb.Plugin.showTips({"type": "error", "content": "/channel/modify 接口异常"});
                    modifyResult.result = "log error,data is null!";
                } else if (data.code != null && data.code == 200) {
                    if (parseInt(data['response']['status']) == 0) {
                        EpgWeb.Plugin.showTips({ "content": "success"});
                        $("button[name=channelQuery]").click();
                        modifyResult.result = "success";
                        if ($data['func'] == "delete_channel") {

                            Zhibo.Util.delRecordTrigger(parseInt(elementId));
                        }
                    } else {
                        EpgWeb.Plugin.showTips({"type": "error", "content": data['response']['error']})
                        modifyResult.result = "log error:" + data['response']['error'];
                    }
                } else {
                    modifyResult.result = "log error code :" + data.code;
                }
                Zhibo.Util.doSubmitLogEntity({ channelId: elementId, descr: modifyResult.result + "|" + JSON.stringify($data), type: Zhibo.Config.FUNC_EXTENT_LOG[$data['func']] })
            });
        },

        getSelectElement: function (elementId) {
            return Zhibo.Config.PageBean.findData("channel_id", elementId)
        },
        getSelectIpElement: function (elementId) {
            return Zhibo.Config.IpPageBean.findData("id", elementId)
        },

        changeElement: function (elementId) {
            var selectElement = Zhibo.Util.getSelectElement(elementId);
            if (selectElement != null) {
                var targetDiv = $("#modifyDiv");
                targetDiv.dialog("open");
                targetDiv.find("input[name=act_type]").val("modify");
                targetDiv.find("input[name=channel_code]").val($.trim(selectElement.channel_code));
                targetDiv.find("input[name=channel_name]").val($.trim(selectElement.channel_name));
                targetDiv.find("input[name=channel_code]").attr("readonly", "readonly");
                targetDiv.find("input[name=channel_addr]").val($.trim(selectElement.channel_addr));
                targetDiv.find("input[name=channel_addr]").attr("readonly", "readonly");
                targetDiv.find("input[name=rtmp]").val($.trim(selectElement.rtmp));
                targetDiv.find("input[name=location]").val($.trim(selectElement.location));
                targetDiv.find("input[name=location]").attr("data-id", $.trim(selectElement.loc_id));
                targetDiv.find("input[name=freeType][value=" + selectElement.freeType + "]").prop("checked", true);
                var regValue = Zhibo.Config.IP_LINK_AREA[selectElement.channel_ip].substr(selectElement.channel_ip.length).replace(/[\[|\]]/g, "");
                if (Zhibo.Config.REGION_LIST.indexOf(regValue) != -1) {
                    targetDiv.find("select[name=server_region2]").val(Zhibo.Config.REGION_LIST.indexOf(regValue));
                    targetDiv.find("select[name=server_region2]").change();
                }
                targetDiv.find("select[name=sourceiplist]").val(selectElement.channel_ip);
                targetDiv.find("input[name=channel_id]").val(selectElement.channel_id);
            }
        },
        addMonitor: function (elementId) {
            var selectElement = Zhibo.Util.getSelectElement(elementId);
            var key = 'monitor', params = {};
            params['id'] = selectElement.channel_id;
            params['name'] = selectElement.channel_name;
            params['rtmp'] = selectElement.rtmp;
            if (!$.trim(params['rtmp'])) {
                EpgWeb.Plugin.showTips({"type": "error", "content": "请填写正确的rtmp流地址"})
                return;
            }
            var dotUrl = 'http://lego.iqiyi.com/peditor/home3?' + selectElement['channel_code'] + '=' + selectElement['channel_ip'] + '&free_type=' + selectElement.freeType + '&channel_id=' + selectElement.channel_id;
            params['dotUrl'] = dotUrl;
            try {
                var monitorArr = Zhibo.Util.Storage.getItem(key);
                if (monitorArr) {
                    if (monitorArr.length > 11) {
                        EpgWeb.Plugin.showTips({type: "error", "content": "12个频道已经添加满"})
                        return;
                    }
                    for (var i in monitorArr) {
                        if (monitorArr[i]['id'] == params['id']) {
                            monitorArr.splice(i, 1);
                            break;
                        }
                    }
                } else {
                    monitorArr = [];
                }
                monitorArr.unshift(params);
                Zhibo.Util.Storage.setItem(key, monitorArr);
                Zhibo.Util.openMonitorPlayer();
                EpgWeb.Plugin.showTips({ "content": "视频监控添加成功"})
            } catch (e) {
                EpgWeb.Plugin.showTips({"type": "error", "content": e.name + ": " + e.message})
            }
        },
        jumpToCodeEdit: function (elementId) {
            var selectElement = Zhibo.Util.getSelectElement(elementId);
            var webUrl = 'http://' + $.trim(selectElement.channel_ip) + ':8080/channel?from_client=true&show=1';
            webUrl += '&channel_code=' + $.trim(selectElement.channel_code);
            webUrl += '&channel_addr=' + $.trim(selectElement.channel_addr);
            window.open(webUrl);
        },

        showCodeDetail: function (ip, code) {
            $("#ip").val(ip);
            $("#code").val(code);
            $("#codeDetail").dialog("open");
        },

        addElement: function () {
            $("#modifyDiv").dialog("open");
            $("#modifyDiv").find("input[name=act_type]").val("add");
        },
        _initEditEvent: function () {
            var self = this;
        },
        getModifyData: function (targetDiv) {
            var obj = {};
            obj.channelName = $.trim(targetDiv.find("input[name=channel_name]").val());
            obj.channelCode = $.trim(targetDiv.find("input[name=channel_code]").val());
            obj.channelAddr = $.trim(targetDiv.find("input[name=channel_addr]").val());
            obj.location = $.trim(targetDiv.find("input[name=location]").val());
            obj.loc_id = $.trim(targetDiv.find("input[name=location]").attr("data-id"));
            if ($.isEmptyObject(obj.location)) {
                obj.loc_id = -1;
            }
            obj.rtmp = $.trim(targetDiv.find("input[name=rtmp]").val());
            obj.serverName = targetDiv.find("select[name=sourceiplist]").val();
            obj.freeType = targetDiv.find("input[name=freeType]:checked").val();
            return obj;
        },

        saveModify: function () {
            var targetDiv = $("#modifyDiv");
            var act_type = targetDiv.find("input[name=act_type]").val();
            var obj = Zhibo.Util.getModifyData(targetDiv);
            var checkArr = [];
            checkArr.push({value: obj.channelName, error: Zhibo.Config.ERROR_MSG.CHANNEL_NAME_REG_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                var rule = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;
                return rule.test(checkValue);
            }   })
            checkArr.push({value: obj.channelCode, error: Zhibo.Config.ERROR_MSG.CHANNEL_CODE_REG_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                var code_rule = /^[A-Za-z0-9\+_-]+$/;
                return code_rule.test(checkValue);
            }   })
            checkArr.push({value: obj.channelAddr, error: Zhibo.Config.ERROR_MSG.CHANNEL_ADDR_ILLEGAL_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                return checkValue.match(/((^rtmp)|(^RTMP)|(^udp)|(^UDP)|(http)|(HTTP)|(^udi)|(^UDI)):\/\//g) != null;
            }   })
            checkArr.push({value: obj.channelAddr, error: Zhibo.Config.ERROR_MSG.CHANNEL_ADDR_PATTERN_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                if (( checkValue.match(/((^udp)|(^UDP)):\/\//g) != null | checkValue.match(/((^udi)|(^UDI)):\/\//g) != null ) && checkValue.split(':').length > 3) {
                    return false;
                }
                return true;
            } });
            checkArr.push({value: obj.serverName, error: Zhibo.Config.ERROR_MSG.CHANNEL_SERVER_EMPTY_ERROR, type: "not_empty"});

            if (obj.rtmp.length > 0) {
                checkArr.push({value: obj.rtmp, error: Zhibo.Config.ERROR_MSG.RTMP_ERROR, type: "self_design", checkCall: function (checkData, checkValue) {
                    return checkValue.match(/((^rtmp)|(^RTMP)):\/\//g) != null
                }})

            }
            if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                return;
            }

            var $req_params = {
                "channel_name": obj.channelName,
                "channel_code": obj.channelCode,
                "channel_addr": obj.channelAddr,
                "channel_ip": obj.serverName,
                "location": obj.location,
                "loc_id": obj.loc_id,
                "type": $("#myTab li.active").attr("value"),
                "freeType": obj.freeType
            };
            if (obj.rtmp.length > 0) {
                $req_params['rtmp'] = obj.rtmp;
            }
            if (act_type == "add") {
                Zhibo.Util.addChannel($req_params)
            } else if (act_type == "modify") {
                var elementId = targetDiv.find("input[name=channel_id]").val();
                var selectElement = Zhibo.Util.getSelectElement(elementId);
                $req_params['src_channel_ip'] = selectElement.channel_ip;
                $req_params['src_channel_addr'] = selectElement.channel_addr;
                $req_params['src_channel_code'] = selectElement.channel_code;
                $req_params['func'] = 'modify_channel';
                Zhibo.Util.modifyChannel($req_params, elementId)
            }
            targetDiv.dialog("close");
        },
        cancelModify: function () {
            $("#modifyDiv").dialog("close");
        },

        IpModify: function (ipDataId) {
            var ipData = Zhibo.Util.getSelectIpElement(ipDataId);
            var area = $("#ipControlForm tr#" + ipData.id + " select").val();
            if (area.length == 0) {
                EpgWeb.Plugin.showTips({type: "error", content: "区域不能为空"});
                return
            }
            Zhibo.Dao.IpModify({"func": "modify", "type": $("#myTab li.active").attr("value"), "ip": ipData.ip, area: parseInt(area)}, function (data) {
                if (data != null && data.code == 200) {
                    EpgWeb.Plugin.showTips({ content: "success"});
                } else {
                    EpgWeb.Plugin.showTips({type: "error", content: data.response.error});
                }
                $("#ip-list").click();
            });
        },
        IpDel: function (ipDataId) {
            SystemDialog.queryConfirm("确认要删除ip么？", function (flag) {
                if (flag) {
                    var ipData = Zhibo.Util.getSelectIpElement(ipDataId);
                    Zhibo.Dao.IpModify({"func": "del", "type": $("#myTab li.active").attr("value"), "ip": ipData.ip}, function (data) {
                        if (data != null && data.code == 200) {
                            EpgWeb.Plugin.showTips({ content: "success"});
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: data.response.error});
                        }
                        $("#ip-list").click();
                    });
                }
            })
        },
        IpAdd: function () {
            var newIpValue = $.trim($("input[name=newIp]").val());
            if (newIpValue.length == 0) {
                EpgWeb.Plugin.showTips({type: "error", content: "ip不能为空"});
                return
            }
            var regIps = /^(((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|[0-9])\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|[0-9]))$/
            var hasError = false;
            if (regIps.test(newIpValue)) {
                var ipArr = newIpValue.split(".");
                var newIpArr = [];
                $.each(ipArr, function (i, element) {
                    newIpArr.push(parseInt(element))
                })
            } else {
                hasError = true;
            }
            if (hasError) {
                EpgWeb.Plugin.showTips({type: "error", content: "ip格式不合法"});
                return;
            }
            newIpValue = newIpArr.join(".");

            var sendData = {"func": "add", "type": $("#myTab li.active").attr("value"), "ip": newIpValue, "area": ""};
            var jsonData = Zhibo.Config.IpPageBean.findData("ip", newIpValue);
            if (jsonData != null) {
                EpgWeb.Plugin.showTips({type: "error", content: "ip已存在"});
                return;
            }

            Zhibo.Dao.IpModify(sendData, function (data) {
                $("input[name=newIp]").val("");
                if (data != null && data.code == 200) {
                    EpgWeb.Plugin.showTips({ content: "success"});
                } else {
                    EpgWeb.Plugin.showTips({type: "error", content: data.response.error});
                }
                $("#ip-list").click();
            });
        },
        openMonitorPlayer: function (btn) {
            //判断是否打开
            if (Zhibo.Config.monitorPlayer == null || Zhibo.ConfigmonitorPlayer.closed) {
                //live2VOD_livelist_monitor
                //http://lego.iqiyi.com/live2VOD/liveList/monitor
                Zhibo.ConfigmonitorPlayer = window.open("/epg/live2VOD_livelist_monitor.html", "openMonitorPlayer");
            }
            else if (btn) {
                Zhibo.Config.monitorPlayer.focus();
            }
        },

        modifyRecord: function (entityId) {
            var arr = $("#recordList").getData();
            var selectElement = null;
            $.each(arr, function (i, element) {
                if (element.id == entityId) {
                    selectElement = element;
                    return false;
                }
            })
            this.cleanRecordForm();
            if (selectElement != null) {
                $('input[name=record_entity_id]').val(entityId);
                $("button[name=record-add]").hide();
                $("button[name=record-edit]").show();
                $("input[name=record_start_time]").datetimepicker("setDate", new Date(selectElement.startTime.replace(/-/g, "/")));
                if (selectElement.endTime != null) {
                    $("input[name=record_end_time]").datetimepicker("setDate", new Date(selectElement.endTime.replace(/-/g, "/")));
                }
                if ((selectElement.notifyType & 1) == 1) {
                    $("input[name=notify_type][value='1']").prop("checked", true);
                }
                if ((selectElement.notifyType & 2) == 2) {
                    $("input[name=notify_type][value='2']").prop("checked", true);
                }
                if ((selectElement.notifyType & 4) == 4) {
                    $("input[name=notify_type][value='4']").prop("checked", true);
                }
                if (selectElement.projectWorkers != null && selectElement.projectWorkers.length > 2) {
                    var workerArr = JSON.parse(selectElement.projectWorkers);
                    $.each(workerArr, function (i, element) {
                        $("input[name=project_workers]").suggest("addValue", element);
                    })
                }
            }
        },
        editRecord: function () {
            var sendData = this.prepareRecordData();
            if (sendData == null) {
                return;
            }
            var entityId = Number($('input[name=record_entity_id]').val());
            var arr = $("#recordList").getData();
            var selectElement = null;
            $.each(arr, function (i, element) {
                if (element.id == entityId) {
                    selectElement = element;
                    return false;
                }
            });
            selectElement.startTime = sendData.startTime;
            selectElement.projectWorkers = sendData.projectWorkers;
            selectElement.notifyType = sendData.notifyType;
            if (sendData.endTime != null) {
                selectElement.endTime = sendData.endTime;
            }
            Zhibo.Dao.editRecord({data: JSON.stringify(selectElement)}, function (data) {
                if (data != null && data.code == "A00000") {
                    EpgWeb.Plugin.showTips({ content: "修改成功"});
                    Zhibo.Util.cleanRecordForm();
                    $('#recordList').jqGrid('setGridParam', {
                        page: 1
                    }).trigger('reloadGrid');
                } else {
                    EpgWeb.Plugin.showTips({ type: "error", content: "修改失败" + (  data != null ? ":" + data.msg : "" )});
                }
            })
        },
        delRecordTrigger: function (channelId) {
            console.log("start delRecordTrigger ")
            var sendData = {"channelId": channelId};
            Zhibo.Dao.delRecord(sendData, function (data) {
                if (data != null && data.code == "A00000") {
                    console.log("end delRecordTrigger success")
                } else {
                    console.log("end delRecordTrigger fail")
                }
            })
        },
        delRecord: function (entityId) {
            var channelId = parseInt($("input[name=record_channel_id]").val());
            var sendData = {"channelId": channelId};
            if (entityId != null) {
                sendData.taskId = entityId
            }
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    Zhibo.Dao.delRecord(sendData, function (data) {
                        if (data != null && data.code == "A00000") {
                            var recordEntityId = Number($('input[name=record_entity_id]').val());
                            if (recordEntityId == entityId) {
                                Zhibo.Util.cleanRecordForm();
                            }
                            EpgWeb.Plugin.showTips({ content: "删除成功"});
                            $('#recordList').jqGrid('setGridParam', {
                                page: 1
                            }).trigger('reloadGrid');
                        } else {
                            EpgWeb.Plugin.showTips({ type: "error", content: "删除失败" + (  data != null ? ":" + data.msg : "" )});
                        }
                    })
                }
            })
        },
        addRecord: function () {
            var channelId = parseInt($("input[name=record_channel_id]").val());
            var sendData = this.prepareRecordData();
            if (sendData == null) {
                return;
            }
            sendData.channelId = channelId;
            Zhibo.Dao.addRecord({data: JSON.stringify(sendData)}, function (data) {
                if (data != null && data.code == "A00000") {
                    EpgWeb.Plugin.showTips({ content: "添加成功"});
                    Zhibo.Util.cleanRecordForm();
                    $('#recordList').jqGrid('setGridParam', {
                        page: 1
                    }).trigger('reloadGrid');
                } else {
                    EpgWeb.Plugin.showTips({ type: "error", content: "添加失败" + (  data != null ? ":" + data.msg : "" )});
                }
            })
        },
        prepareRecordData: function () {
            var startTime = $("input[name=record_start_time]").val().trim();
            var endTime = $("input[name=record_end_time]").val().trim();
            var workersArr = $("span.qui-tag");
            var newDataArr = [];
            if (workersArr.length > 0) {
                $.each(workersArr, function (i, element) {
                    newDataArr.push({ id: $(element).attr("data-tag-id"), label: $(element).attr("data-tag-label") });
                })
            }
            var notifyTypeArr = $("input[name=notify_type]:checked");
            var notifyType = 0;
            if (notifyTypeArr.length > 0) {
                $.each(notifyTypeArr, function (i, element) {
                    notifyType += parseInt($(element).val());
                })
            }
            if (newDataArr.length > 0 && notifyType == 0) {
                EpgWeb.Plugin.showTips({ type: "error", content: "请选择通知方式"});
                return null;
            }
            if (!EpgWeb.Plugin.Validate.checkDateFormat(startTime)) {
                EpgWeb.Plugin.showTips({ type: "error", content: "开始时间格式错误"});
                return null;
            }
            var sendData = { "startTime": startTime, "projectWorkers": JSON.stringify(newDataArr), notifyType: notifyType};
            if (endTime.length > 0) {
                if (!EpgWeb.Plugin.Validate.checkDateFormat(endTime)) {
                    EpgWeb.Plugin.showTips({ type: "error", content: "结束时间格式错误"});
                    return null;
                }
                sendData.endTime = endTime;
            }
            return sendData;
        },

        cleanRecordForm: function () {
            $("input[name=record_start_time]").val("");
            $("input[name=record_end_time]").val("");
            $("button[name=record-add]").show();
            $("button[name=record-edit]").hide();
            $('input[name=record_entity_id]').val("");
            $('input[name=project_workers]').val("");
            $("a.qui-tag-remove").click();
            $("input[name=notify_type]:checked").click()
        },
        Storage: {
            setItem: function (k, v) {
                var strValue = JSON.stringify(v);
                localStorage.setItem(k, strValue);
            },
            removeItem: function (k) {
                localStorage.removeItem(k);
            },
            getItem: function (k) {
                return JSON.parse(localStorage.getItem(k));
            }
        },
        openHistory: function (entityId) {
            $("#vodLogDiv").dialog("open");
            $('#logList').jqGrid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: { paramsObj: JSON.stringify({ EQI_channelId: entityId}) }
            }).trigger('reloadGrid');
        },
        openRecord: function (entityId) {
            $("#vodRecordDiv").dialog("open");
            this.cleanRecordForm();
            $('input[name=record_channel_id]').val(entityId);
            $('#recordList').jqGrid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: {channelId: entityId}
            }).trigger('reloadGrid');
        },
        submitAddLog: function (dataArr, waitData) {
            $.each(dataArr, function (i, entity) {
                if (waitData.channel_code == entity.channel_code && waitData.channel_ip == entity.channel_ip) {
                    waitData.channel_id = entity.channel_id;
                    var submitLogData = { channelId: waitData.channel_id, type: Zhibo.Config.VOD_LOG_TYPE.addElement, descr: "suc|" + JSON.stringify(waitData) };
                    Zhibo.Util.doSubmitLogEntity(submitLogData);
                    return true;
                }
            })
        },
        doSubmitLogEntity: function (submitLogData) {
            Zhibo.Dao.submitLogEntity(submitLogData, function (data) {
                    if (data == null || data.code != "A00000") {
                        console.warn("submitLogEntity error");
                    } else {
                        console.log("submitLogEntity suc");
                    }
                }
            )
        },
        decodeDescription: function (description) {
            var elementArr = description.split("|");
            var newArr = [];
            if (elementArr.length == 2) {
                newArr.push(elementArr.shift());
            } else if (elementArr.length >= 3) {
                newArr.push(elementArr.shift());
                newArr.push(elementArr.shift());
            }
            var jsonObj = JSON.parse(elementArr.join("|"));
            var list = JSON.parse(jsonObj.list);
            if( list.length > 2){
                var newFold = [];
                var nodeStart = -100;
                var nodeEnd = -100;
                var curIndex = 0;
                $.each(list, function (i, element) {
                    curIndex = element;
                    if (curIndex > nodeEnd + 1) {
                        if (nodeStart >= 0) {
                            newFold.push({ start: nodeStart, end: nodeEnd});
                        }
                        nodeStart = curIndex;
                        nodeEnd = curIndex;
                    } else if (curIndex == nodeEnd + 1) {
                        nodeEnd = curIndex;
                    }
                })
                if (nodeEnd >= nodeStart) {
                    newFold.push({ start: nodeStart, end: nodeEnd});
                }
                jsonObj.list = newFold;
            }
            newArr.push(JSON.stringify(jsonObj));
            return newArr.join("|");
        },
        openWrapSys:function(elementId){
            var req_publicparams = Zhibo.Util.buildPublicParams(elementId);
            window.open('/epg/dadian_wrap_sys.html?' + req_publicparams['channel_code'] + '=' + req_publicparams['channel_ip'] + '&free_type=' + req_publicparams["freeType"] + '&channel_id=' + elementId + '&cn=' + req_publicparams['channel_name'] + '&location=' + req_publicparams['location'] + '&locationCategory=' + req_publicparams['locationCategory'], "epg_wrap" + req_publicparams['channel_code']);

        }
    });
});